﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 文华财经数据解析.utils.WHDataServer
{
    internal class PacketParse
    {
        private List<byte[]> packets=new List<byte[]>();


        private List<byte[]> tempData=new List<byte[]>();
        //接收数据构建包
        public void Recive(byte[] data,int offset,int length) 
        {
            if (length > 0)
            {
                byte[] currdata = new byte[length];
                Array.Copy(data, offset, currdata, 0, length);
                tempData.Add(currdata);
                while (true)
                {
                    int currLenth = PacketHelper.GetContentLength(tempData);
                    if (currLenth >= 8)
                    {
                        int packetlen = PacketHelper.GetPackLength(tempData);

                        if (packetlen <= currLenth) //数据包完整构建一个包
                        {
                            byte[] packet = PacketHelper.BuildPack(tempData, packetlen);
                            packets.Add(packet);
                            if (packetlen == currLenth)
                            {
                                tempData.Clear();
                            }
                            else
                            {
                                byte[] alldata = PacketHelper.BuildPack(tempData, currLenth);
                                byte[] nextData = new byte[currLenth - packetlen];
                                Array.Copy(alldata, packetlen, nextData, 0, currLenth - packetlen);
                                tempData.Clear();
                                tempData.Add(nextData);
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }

        //获取包
        public byte[] push() 
        {
            if (packets.Count>0)
            {
                var packet= packets[0];
                packets.RemoveAt(0);
                return packet;
            }
            else
            {
                return null;
            }
        }
    }
}
